﻿using FluentValidation;
using MediatR;
using BuildBlock.CQRS;

namespace BuildBlock.PipelineBeheviour
{
    public class ValidatorBehavior<TRequest, TResponse>(IEnumerable<IValidator<TRequest>> validators)
        : IPipelineBehavior<TRequest, TResponse>
        where TRequest : ICommand<TResponse>
    {
        //在http请求中，插入验证器，验证请求参数是否合法
        //TRequest request 请求
        //RequestHandlerDelegate<TResponse> next 下一个处理程序 一般指的是处理请求的handler
        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
        {
            var context = new ValidationContext<TRequest>(request);
            var validationResults = await Task.WhenAll(validators.Select(v => v.ValidateAsync(context, cancellationToken)));
            var failures = validationResults
                .Where(r => r.Errors.Any())
                .SelectMany(r => r.Errors)
                .ToList();

            if (failures.Any())
            {
                throw new ValidationException(failures);
            }
            return await next();

        }
    }
}
